package com.gitee.feizns.utils.reflect;

import java.lang.reflect.Field;

/**
 * @author feizns
 * @since 2019/5/12 0012
 */
public abstract class FieldUtils {

    /**
     * 获取属性
     * @param obj
     * @param name
     * @return
     */
    public static final Field getField(Object obj, String name) {
        Class<?> clz = obj.getClass();

        while ( clz != Object.class ) {
            try {
                return clz.getDeclaredField(name);
            } catch (NoSuchFieldException e) {
                clz = clz.getSuperclass();
            }
        }

        return null;
    }

    /**
     * 获取字段的值
     * @param obj
     * @param field
     * @param <T>
     * @return
     */
    public static final <T> T getFieldData(Object obj, Field field) {
        try {
            field.setAccessible(true);
            return (T) field.get(obj);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取属性的值
     * @param obj
     * @param name
     * @param <T>
     * @return
     */
    public static final <T> T getFieldData(Object obj, String name) {
        Field field = getField(obj, name);
        return field != null ? getFieldData(obj, field) : null;
    }

    /**
     * 获取字段的值
     * @param obj
     * @param name
     * @param resultType
     * @param <T>
     * @return
     */
    public static final <T> T getFieldData(Object obj, String name, Class<T> resultType) {
        Field field = getField(obj, name);
        if ( field != null ) {
            Object data = getFieldData(obj, field);
            if ( data != null && resultType.isAssignableFrom(data.getClass()) ) {
                return (T) data;
            }
        }
        return null;
    }

}
